package ficheros;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;


// Clase que se encarga de guardar y cargar ficheros en binario.
public class FicherosBinarios 
{

	//---------------------------
	//-----     METODOS     -----
	//---------------------------	
	public static String[] stringABinario(String sEntrada)
	{
        byte[] bytes = sEntrada.getBytes();
        String[] arrayBinario = new String[bytes.length];
        for (int i = 0; i < bytes.length; i++) 
        {
            arrayBinario[i] = Integer.toBinaryString(bytes[i]);
        }
        return arrayBinario;
	}
	
	public static String binarioAString(ArrayList<String> arrayBinario)
	{
		byte[] bytes = new byte[arrayBinario.size()];
        for (int i = 0; i < arrayBinario.size(); i++) 
        {
            bytes[i] = Byte.parseByte(arrayBinario.get(i), 2);
        }
        String s = new String(bytes);
        return s;
	}
	
	public static void guardar(String ruta, ArrayList<String> listaStrings) throws FileNotFoundException
	{
		PrintWriter pw;
		pw = new PrintWriter(ruta);
		for (int i = 0; i < listaStrings.size(); i ++) 
		{
			String[] binario = stringABinario(listaStrings.get(i));
			for (int j = 0; j < binario.length; j ++)
			{
				pw.write(binario[j]);
				pw.write("\n");
			}
			pw.write("\n");
		}
		pw.close();
	}
	
	@SuppressWarnings("resource")
	public static ArrayList<String> cargar(String ruta) throws IOException
	{
		ArrayList<String> listString = new ArrayList<String>();
		ArrayList<String> listaBinario = new ArrayList<String>();
		BufferedReader bReader = new BufferedReader(new FileReader(ruta));
		
		while (bReader.ready()) {
			Scanner scanner = new Scanner(bReader.readLine());
			if (scanner.hasNext()) listaBinario.add(scanner.next());
			else {
				listString.add(binarioAString(listaBinario));
				listaBinario.clear();
			}
		}
		
		bReader.close();
		return listString;
	}
	
	
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		// TODO Auto-generated method stub
		
		ArrayList<String> instruccionesPila = new ArrayList<String>();
		instruccionesPila.add("apila(3)");
		instruccionesPila.add("desapilaVar(1)");
		try {
			FicherosBinarios.guardar("prueba.dat", instruccionesPila);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			instruccionesPila = FicherosBinarios.cargar("prueba.dat");
			System.out.println(instruccionesPila.size());
			for (int i = 0; i < instruccionesPila.size(); i ++) {
				System.out.println(instruccionesPila.get(i));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

} //Class FicherosBinarios
